package main

import (
	"flag"
	"fmt"
	"gopkg.in/natefinch/lumberjack.v2"
	"io"
	"log"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"syscall"
	"time"
)

var (
	configFile = flag.String("config", "/etc/config/dahuavto", "Path to config file")
	logger     = setupLogger("")
)

func memoryMonitor() {
	go func() {
		for {
			var m runtime.MemStats
			runtime.ReadMemStats(&m)
			if m.Alloc > 6*1024*1024 {
				logger.Printf("Memory usage high: %v MB", m.Alloc/1024/1024)
				runtime.GC()
			}
			time.Sleep(30 * time.Second)
		}
	}()
}

func setupLogger(logPath string) *log.Logger {
	if logPath != "" {
		if err := os.MkdirAll(filepath.Dir(logPath), 0755); err != nil {
			log.Fatalf("Failed to create log directory: %v", err)
		}
		logOutput := &lumberjack.Logger{
			Filename:   logPath,
			MaxSize:    1,
			MaxBackups: 1,
			MaxAge:     1,
			Compress:   false,
		}
		return log.New(io.MultiWriter(logOutput, os.Stdout), "", log.LstdFlags)
	}
	return log.New(os.Stdout, "", log.LstdFlags)
}

func main() {
	flag.Parse()
	memoryMonitor()
	cfg, err := LoadConfigFromUCI(*configFile)
	if cfg.LogOut != "" {
		logger = setupLogger(cfg.LogOut)
	}
	fmt.Println(cfg.GpioOut, cfg.LogOut)
	log.SetOutput(logger.Writer())
	if err != nil {
		logger.Fatalf("解析配置文件失败: %v", err)
	}
	// 启动 HTTP 服务器
	addr := ":2669"
	if cfg.Listen != "" {
		addr = cfg.Listen
	}
	server := NewServer(cfg)
	// 处理退出信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-quit
		logger.Println("收到退出信号，正在关闭客户端连接...")
		server.Close()
		os.Exit(0)
	}()
	// 启动服务器
	logger.Fatal(server.Start(addr))
}
